package datasink;

import static station.DataMessage.DATA_LENGTH;
import static station.DataMessage.NEXT_SLOT_BYTE;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import station.DataMessage;


public class DataSink  {

	private static byte[] buf;
	private static byte slot = 0;
	private static long time = 0;
    private static byte[] data;


    public static void main(String args[]) {
        if (args.length > 0 && !args[0].equals("--help") && args.length < 2) {
        	
            int udpPortSink = Integer.parseInt(args[0]);
            boolean running = true;
            byte buffer[] = new byte[33];
            LogBuilder lb = new LogBuilder();
            data = new byte[24];
            
            System.out.println("DataSink ist listening on Port " + args[0] + "...");
			try {
				
				DatagramSocket udpSocket = new DatagramSocket(udpPortSink);
				DatagramPacket packet = new DatagramPacket(buffer,
						buffer.length);
				
                while (running) {
                    udpSocket.receive(packet);
            		slot = 0;
            		time = 0;
            		buf = packet.getData();
            		for (int i = 0; i < DATA_LENGTH; i++) {
            				data[i] = buf[i];
            		}
            		slot = buf[NEXT_SLOT_BYTE];
            		time = DataMessage.getTime(buf);
                    lb.log(data, slot, time);
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            System.err.println("Usage: java datasink.DataSink <udp port sink>");
        }
    }

}
